package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.aliyun.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.mapper.WmchannelMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmchannelMapper wmchannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 自媒体文章审核
     *
     * @param id
     */
    @Override
    @Async
    public void autoScanWmNews(Integer id) {

        //查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null){
            throw new RuntimeException("文章不存在");
        }

        //判断文章是不是处于已经发布,待审核的阶段
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //从内容中提取纯文本内容,和纯图片内容
            Map<String, Object> textAndImages = handTextAndImages(wmNews);

            //自管理敏感词过滤
            Boolean content = handleSensitiveScan((String) textAndImages.get("content"), wmNews);
            if (!content)return;

            //审核文本内容,调用阿里云接口
            Boolean textContent = handleTextScan((String) textAndImages.get("content"), wmNews);
//            if (!textContent)return;

            //审核图片内容,调用阿里云接口
            Boolean images = handleImageScan((List<String>) textAndImages.get("images"), wmNews);
//            if (!images)return;

            //审核成功,保存app端文章内容
            ResponseResult responseResult = saveAppArticle(wmNews);
            if(!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }

            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,(short) 9,"审核成功");


        }


    }

    /**
     * 自管理敏感词汇
     * @param content
     * @param wmNews
     */
    private Boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> collect = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //????
        //初始化敏感词库
        SensitiveWordUtil.initMap(collect);

        //查看文章中是否含有敏感词
        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(content);
        if (stringIntegerMap.size()>0){
            updateWmNews(wmNews, (short) 2,"文章中含有违规词汇"+stringIntegerMap);
            flag = false;
        }
        return flag;
    }

    /**
     * 审核成功,保存app端文章信息
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        //属性拷贝
        BeanUtils.copyProperties(wmNews,dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmchannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel!=null){
            dto.setChannelName(wmChannel.getName());
        }
        //作者信息
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser!=null){
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if (wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = iArticleClient.saveArticle(dto);
        return responseResult;

    }

    /**
     * 审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private Boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;

        if (images == null || images.size() == 0){
            return flag;
        }

        //下载图片 从minio
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> list = new ArrayList<>();

        for (String image : images) {
            byte[] bytes = fileStorageService.downLoadFile(image);

            //图片识别
            String result = null;
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            try {
                BufferedImage BufferedImang = ImageIO.read(in);
                result= tess4jClient.doOCR(BufferedImang);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //过滤文字
            Boolean aBoolean = handleSensitiveScan(result, wmNews);
            if (!aBoolean){
                return aBoolean;
            }

            list.add(bytes);
        }

        //审核图片
        try {
            Map map = greenImageScan.imageScan(list);

            if (map != null){
                //内容违规
                if (map.get("suggestion").equals("block")){
                    flag = false;
                    updateWmNews(wmNews,(short)2,"文章中存在违规内容");
                }
                //不确定是否违规
                if (map.get("suggestion").equals("review")){
                    flag = false;
                    updateWmNews(wmNews,(short) 3,"当前文章中存在不确定内容");
                }
            }

        } catch (Exception e) {
            flag =false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 审核文本
     * @param content
     * @param wmNews
     * @return
     */
    private Boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;

        if (content.length()==0){
            return flag;
        }

        //审核文本
        try {
            Map map = greenTextScan.greeTextScan(content);
            if (map != null){
                //内容违规
                if (map.get("suggestion").equals("block")){
                    flag = false;
                    updateWmNews(wmNews,(short)2,"文章中存在违规内容");
                }
                //不确定是否违规
                if (map.get("suggestion").equals("review")){
                    flag = false;
                    updateWmNews(wmNews,(short) 3,"当前文章中存在不确定内容");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }

        return flag;
    }

    private void updateWmNews(WmNews wmNews, short status, String reson) {
        wmNews.setStatus(status);
        wmNews.setReason(reson);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从内容中提取纯文本内容,和纯图片内容
     * @param wmNews
     */
    private Map<String,Object> handTextAndImages(WmNews wmNews) {

        //储存纯文本的容器
        StringBuilder stringBuilder = new StringBuilder();

        String title = wmNews.getTitle();
        stringBuilder.append(title);
        //储存图片信息
        List<String> image = new ArrayList();

        if (StringUtils.isBlank(wmNews.getContent())){
            List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("text")){
                    stringBuilder.append(map.get("value"));
                }
                if (map.get("type").equals("image")){
                    image.add((String) map.get("value"));
                }
            }
        }


        if (!StringUtils.isBlank(wmNews.getImages())){
            String[] images = wmNews.getImages().split(",");
            image.addAll(Arrays.asList(images));
        }


        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",image);
        return resultMap;

    }
}
